package com.example.myenglishbook;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.ItemTouchHelper;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.SearchView;
import android.widget.Toast;

import com.example.myenglishbook.adapter.EmptyRecylerViewAdapter;
import com.example.myenglishbook.adapter.ListRecyclerViewAdapter;
import com.example.myenglishbook.database.Words;
import com.example.myenglishbook.databinding.ActivityMainBinding;
import com.example.myenglishbook.utils.StringUtils;
import com.example.myenglishbook.viewModel.WordsViewModel;

import java.util.List;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private ActivityMainBinding binding;
    private WordsViewModel wordsViewModel;
    private List<Words> data;
    private LiveData<List<Words>> filterWords;
    private boolean isCardView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        initView();
    }

    private void initView() {
        wordsViewModel = new ViewModelProvider(this, new ViewModelProvider.AndroidViewModelFactory(getApplication())).get(WordsViewModel.class);

        binding.recylcerView11.setLayoutManager(new LinearLayoutManager(MainActivity.this));

        filterWords=wordsViewModel.getData();
        filterWords.observe(this, new Observer<List<Words>>() {
            @Override
            public void onChanged(List<Words> words) {
                data = words;
                if (words != null && words.size() != 0) {
                    binding.recylcerView11.setAdapter(new ListRecyclerViewAdapter(data, isCardView, wordsViewModel));
                } else {
                    binding.recylcerView11.setAdapter(new EmptyRecylerViewAdapter());
                }
            }
        });
        binding.switch11.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                isCardView = isChecked;
                if (data != null && data.size() != 0) {
                    binding.recylcerView11.setAdapter(new ListRecyclerViewAdapter(data, isCardView, wordsViewModel));
                }
            }
        });
        binding.clearb.setOnClickListener(this);
        binding.insertb.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.insertb:
                add();
                break;
            case R.id.clearb:
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(R.string.are_you_sure_to_delete).setNegativeButton(R.string.sure, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        clear();
                    }
                }).setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).create().show();
                break;
        }
    }

    private void insert(Words... words) {
        wordsViewModel.insert(words);
    }

//    private void update(Words... words) {
//        wordsViewModel.update(words);
//    }

    private void clear() {
        wordsViewModel.clear();
    }

    private void delete(Words... words) {
        wordsViewModel.delete(words);
    }

    private void add() {//添加单词
        //弹窗初始化
        AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.add_alert_dialog_view, null);
        EditText wordEditor = view.findViewById(R.id.wordEditor);
        EditText meaningEditor = view.findViewById(R.id.meaningEditor);
        builder.setTitle(R.string.add_word);
        builder.setView(view);
        builder.setNegativeButton(R.string.add, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (StringUtils.isEmpty(wordEditor.getText().toString()) || StringUtils.isEmpty(meaningEditor.getText().toString())) {
                    Toast.makeText(MainActivity.this, R.string.warn_not_empty, Toast.LENGTH_SHORT).show();
                } else {
                    Words word = new Words(wordEditor.getText().toString(), meaningEditor.getText().toString());
                    insert(word);
                }
            }
        });
        builder.setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.create().show();
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu, menu);
        SearchView searchView = (SearchView) menu.findItem(R.id.app_bar_search).getActionView();
        searchView.setMaxWidth(500);
        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                return true;//false表示未处理完会往下传递，true表示处理完不会往下传递
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                filterWords = wordsViewModel.findWordsWithPatten(newText);
                filterWords.removeObservers(MainActivity.this);
                filterWords.observe(MainActivity.this, new Observer<List<Words>>() {
                    @Override
                    public void onChanged(List<Words> words) {
                        data = words;
                        if (words != null && words.size() != 0) {
                            binding.recylcerView11.setAdapter(new ListRecyclerViewAdapter(data, isCardView, wordsViewModel));
                        } else {
                            binding.recylcerView11.setAdapter(new EmptyRecylerViewAdapter());
                        }
                    }
                });
                return true;
            }
        });

        //滑动删除
        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0,ItemTouchHelper.START | ItemTouchHelper.END) {

            @Override
            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {
                return false;
            }

            @Override
            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle(R.string.warn_delete).setNegativeButton(R.string.sure, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Words wordToDelete=data.get(viewHolder.getAdapterPosition());
                        delete(wordToDelete);
                    }
                }).setPositiveButton(R.string.cancel, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startActivity(new Intent(MainActivity.this,MainActivity.class));
                    }
                }).create().show();
            }
        }).attachToRecyclerView(binding.recylcerView11);//记得附加绑定recyclerView

        return super.onCreateOptionsMenu(menu);
    }

}